package dao;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class XmlFactory {
	private static final String PATH_BASE = "C:\\XML\\";

	private static XmlFactory instance;

	public static XmlFactory getInstance() {
		if (instance == null)
			instance = new XmlFactory();
		return instance;
	}

	private DocumentBuilderFactory builderFactory;
	private DocumentBuilder builder;
	private TransformerFactory transformerFactory;
	private Transformer transformer;

	private XmlFactory() {
		try {
			builderFactory = DocumentBuilderFactory.newInstance();
			builder = builderFactory.newDocumentBuilder();
			transformerFactory = TransformerFactory.newInstance();
			transformer = transformerFactory.newTransformer();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Document newDocument() {
		return builder.newDocument();
	}

	public Document parse(String filename) throws SAXException, IOException {
		return builder.parse(PATH_BASE + filename);
	}

	public Document parse(InputStream is) throws SAXException, IOException {
		return builder.parse(is);
	}

	public void save(Document doc, String filename) throws IOException, TransformerException {
		Source source = new DOMSource(doc);
		Result result = new StreamResult(new FileWriter(new File(PATH_BASE + filename)));
		transformer.transform(source, result);
	}
}